package com.example.lenovo.downloaddemo.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.lenovo.downloaddemo.R;
import com.example.lenovo.downloaddemo.activity.ProductInfoActivity;
import com.example.lenovo.downloaddemo.adapter.SearchAdapter;
import com.example.lenovo.downloaddemo.bean.Customer;
import com.example.lenovo.downloaddemo.bean.SearchBean;
import com.example.lenovo.downloaddemo.http.datasource.MDataSource;
import com.example.lenovo.downloaddemo.http.okhttp.utils.AppContext;
import com.example.lenovo.downloaddemo.http.okhttp.utils.Collintion;
import com.example.lenovo.downloaddemo.http.okhttp.utils.CommonUtils;
import com.example.lenovo.downloaddemo.http.okhttp.utils.MD5;
import com.example.lenovo.downloaddemo.http.okhttp.utils.ToastUtil;
import com.example.lenovo.downloaddemo.myview.MyEditText;
import com.example.lenovo.downloaddemo.sqlite.LoadListCallBack;
import com.example.lenovo.downloaddemo.util.StatusBarUtil;
import com.example.lenovo.downloaddemo.util.TimeUtil;
import com.example.lenovo.downloaddemo.view.TitleBarView;
import com.google.gson.Gson;


import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Request;

public class SearchFragment extends Fragment implements View.OnClickListener {

//    @Bind(R.id.search_et)
//    EditText search_et;
    @Bind(R.id.search_Titbar)
    TitleBarView search_Titbar;
    @Bind(R.id.search_listview)
    ListView search_listview;
    @Bind(R.id.search_et)
    MyEditText search_et;

    @Bind(R.id.hot)
    LinearLayout hot;//
    @Bind(R.id.hot_search)
    TextView hot_search;//热门搜索
    @Bind(R.id.QQ)
    TextView QQ;//QQ
    @Bind(R.id.wechat)
    TextView wechat;//微信
//    @Bind(R.id.Game)
//    TextView Game;//游戏
    private SearchAdapter adapter;
    private List<SearchBean.DataBean> data;

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String returnMessage= (String) msg.obj;
                Gson gson=new Gson();
                SearchBean bean=gson.fromJson(returnMessage,SearchBean.class);
                if(bean.getCode()==200){
                    data=bean.getData();
                    adapter=new SearchAdapter(AppContext.getInstance(),data);
                    search_listview.setAdapter(adapter);
                }else{

                }
            }else if(msg.what==2){
                String returnMessage= (String) msg.obj;
                Gson gson=new Gson();
                SearchBean bean=gson.fromJson(returnMessage,SearchBean.class);
                if(bean.getCode()==200){
                    data=bean.getData();
                    if(data!=null) {
                        for (int i = 0; i <data.size(); i++) {
                            Intent intent =new Intent(getActivity(),ProductInfoActivity.class);
                            intent.putExtra("goodsid",data.get(i).getGood_id());
                            startActivity(intent);
                        }
                    }
//                    adapter=new SearchAdapter(AppContext.getInstance(),data);
//                    search_listview.setAdapter(adapter);
                }else{

                }
            }
        }
    };


    public static SearchFragment instance;

    private Context context;
    private View view;

    public static SearchFragment getInstance() {
        if (null == instance) {
            instance = new SearchFragment();
        }
        return instance;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == view) {
            view = inflater.inflate(R.layout.search_fragment, container, false);
            ButterKnife.bind(this, view);
            initView();
        } else {
            if (null != view.getParent()) {
                ((ViewGroup) view.getParent()).removeAllViews();
            }

        }
        instance = this;
        return view;
    }

    private String allString;
    private void getSearchList(String goodName){
        HashMap<String, String> map = new HashMap<>();
        map.put("model", "index");
        map.put("method", "search");
        map.put("good_name", goodName);
        map.put("time",new TimeUtil().getMoment());
        Collintion collintion=new Collintion();

        allString=collintion.Sort(map)+"ad1af567dc7bfedd5e760fc1f48a59ae";
        String sign= MD5.GetMD5Code(MD5.GetMD5Code(allString));
        Log.e("拼接字符串",allString);
        Log.e("签名===",sign);
        map.put("sign",sign);
        MDataSource<Customer> dataSource = new MDataSource<>(AppContext.getInstance());
        dataSource.postData(map, new LoadListCallBack() {
            @Override
            public void loadList(List list) {

            }

            @Override
            public void systemError(Request request, String errorInfo, Exception e) {
                Log.e("error", "systemError: " + errorInfo);
                e.printStackTrace();
            }

            @Override
            public void retLoad(String code) {

            }

            @Override
            public void loadString(String string) {
                Log.e("搜索", "loadString 获取结果 : " + string);

                Message message=Message.obtain();
                message.what=1;
                message.obj=string;
                mHandler.sendMessage(message);





            }
        });
    }

    private String all;
    private void getSingleInfo(String goodName){
        HashMap<String, String> map = new HashMap<>();
        map.put("model", "index");
        map.put("method", "search");
        map.put("good_name", goodName);
        map.put("time",new TimeUtil().getMoment());
        Collintion collintion=new Collintion();

        all=collintion.Sort(map)+"ad1af567dc7bfedd5e760fc1f48a59ae";
        String sign= MD5.GetMD5Code(MD5.GetMD5Code(all));
        Log.e("拼接字符串",all);
        Log.e("签名===",sign);
        map.put("sign",sign);
        MDataSource<Customer> dataSource = new MDataSource<>(AppContext.getInstance());
        dataSource.postData(map, new LoadListCallBack() {
            @Override
            public void loadList(List list) {

            }

            @Override
            public void systemError(Request request, String errorInfo, Exception e) {
                Log.e("error", "systemError: " + errorInfo);
                e.printStackTrace();
            }

            @Override
            public void retLoad(String code) {

            }

            @Override
            public void loadString(String string) {
                Log.e("单个搜索", "loadString 获取结果 : " + string);

                Message message=Message.obtain();
                message.what=2;
                message.obj=string;
                mHandler.sendMessage(message);





            }
        });
    }

    private void initView() {
        StatusBarUtil.setMargin(context,search_Titbar);
        search_Titbar.setTitle(AppContext.getInstance().getResources().getString(R.string.search));
        search_Titbar.showBackButton(false);


        hot_search.setText(AppContext.getInstance().getResources().getText(R.string.hot_search));
        QQ.setText(AppContext.getInstance().getResources().getText(R.string.qq));
        wechat.setText(AppContext.getInstance().getResources().getText(R.string.wechat));
        QQ.setOnClickListener(this);
        wechat.setOnClickListener(this);
        search_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(AppContext.getInstance(),ProductInfoActivity.class);
                intent.putExtra("goodsid",data.get(i).getGood_id());
                startActivity(intent);
                search_et.setText("");
            }
        });

        // 自动提示适配器
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, str);
        // 支持拼音检索
        TextWatcher watcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.e("beforeTextChanged","beforeTextChanged");
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.e("onTextChanged","onTextChanged");
                hot.setVisibility(View.GONE);
                search_listview.setVisibility(View.VISIBLE);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                Log.e("afterTextChanged",search_et.getText().toString());
                if(!TextUtils.isEmpty(search_et.getText().toString())) {
                    if(CommonUtils.isNetOk(AppContext.getInstance())) {
                        getSearchList(search_et.getText().toString());
                    }


                }else {
                    if(data!=null) {
                        data.clear();
                        adapter.notifyDataSetChanged();
                        search_listview.setVisibility(View.GONE);
                        hot.setVisibility(View.VISIBLE);
                    }

                }


            }
        };
        search_et.addTextChangedListener(watcher);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!TextUtils.isEmpty(search_et.getText())){
            search_listview.setVisibility(View.VISIBLE);

            hot.setVisibility(View.GONE);
        }else{
            search_listview.setVisibility(View.GONE);

            hot.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("onPause","onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e("onStop","onStop");
        if(!TextUtils.isEmpty(search_et.getText().toString())) {
            search_et.setText("");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.QQ:
                if(CommonUtils.isNetOk(AppContext.getInstance())) {
                    getSingleInfo("QQ");
                }
                break;
            case R.id.wechat:
                if(CommonUtils.isNetOk(AppContext.getInstance())) {
                    getSingleInfo("教育儿童");
                }
                break;
        }
    }
}
